package com.ticket.sass.provider.controller;

import com.github.xiaoymin.knife4j.annotations.ApiSupport;
import com.ticket.sass.common.exception.enums.ErrorCode;
import com.ticket.sass.common.exception.exception.BadRequestException;
import com.ticket.sass.provider.business.FileUpLoadBusiness;
import com.ticket.sass.provider.business.impl.FileUpLoadBusinessImpl;
import com.ticket.sass.provider.config.AppConfig;
import com.ticket.sass.provider.dto.input.file.FileNameInput;
import com.ticket.sass.provider.model.QiNiuModel;
import com.ticket.sass.provider.model.ResultModel;
import com.ticket.sass.provider.util.EscapeUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Objects;
import java.util.Random;
import java.util.UUID;

/**
 * @author ywb
 * @date 2022-09-28 10:08
 */
@RestController
@ApiSupport(order = 2)
@Api(tags = {"文件上传-模块"})
public class FileUpLoadController {
    
    final FileUpLoadBusiness business;
    
    public FileUpLoadController(FileUpLoadBusinessImpl business) {
        this.business = business;
    }
    
    @GetMapping("/qiniu/token")
    @ApiOperation("获取七牛token")
    public ResultModel<QiNiuModel> getToken() {
        return ResultModel.success(
            business.qiNiuModel()
        );
    }
    
    @GetMapping("/qiniu/file-name")
    @ApiOperation("文件名")
    public ResultModel<String> fileName(
        @Valid FileNameInput input
    ) {
        if (Objects.isNull(AppConfig.FILE_NAME_MAP.get(input.getRoute()))){
            throw new BadRequestException(
                ErrorCode.BUSINESS_ERROR,
                EscapeUtil.errorMessage("route", "请输入约定好的参数！")
            );
        }
        
        // 获取当前日期
        LocalDate currentDate = LocalDate.now();
        // 将日期格式化成字符串，例如：20240424
        String formattedDate = currentDate.format(DateTimeFormatter.ofPattern("yyyyMMdd"));
        
        return ResultModel.success(
            "temp/" + formattedDate + "/" + AppConfig.FILE_NAME_MAP.get(input.getRoute()) + fileName()
        );
    }
    
    public static String fileName() {
        String uuid = UUID.randomUUID().toString();
        String randomNum = Integer.toString(new Random().nextInt(10000));
        String hash = Integer.toString(uuid.hashCode() & Integer.MAX_VALUE);
        return hash + randomNum;
    }
}
